package weekthree;

public class ConstructBinaryTreeFromPreAndInorder_105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0) return null;
        return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    private TreeNode build(int[] preorder, int l1, int r1, int[] inorder, int l2, int r2) {
        if (l1 > r1) return null;
        TreeNode root = new TreeNode(preorder[l1]);
        // if(l1==r1 && l2==r2) return root;
        int mid = l1;
        for (int i = l2; i <= r2; i++) {
            if (inorder[i] == preorder[l1]) {
                mid = i;
                break;
            }
        }
        int leftSize = mid - l2;
//        int rightSize = r2 - mid;
        root.left = build(preorder, l1 + 1, l1 + leftSize, inorder, l2, mid - 1);
        root.right = build(preorder, l1 + leftSize + 1, r1, inorder, mid + 1, r2);
        return root;
    }

    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
